/* =================================================
 * Package:			dk.iha.toksEditor
 * File:			MainView.java
 * Description:		This is the activity used to 
 * 					navigating to the other activities.
 * 
 * Responsible
 * =================================================
 * Name:			Vinnie Juul
 * Study number:	09767
 * 
 * Assistant(s)
 * =================================================
 * Name:			Bjarke Jensen
 * Study number:	09676
 * 
 * Name:			Jakob Sulby
 * Study number:	09136
 */

package dk.iha.toksEditor;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainView extends Activity
{
	private final int mLogIn = 1;
	private final int mPatientData = 2;
	private final int mFavoritePatient = 3;
	private final int mUnfinishedPatient = 5;
	private User user;
	private Patient mCurrentPatient;
	private DataBaseConnection DBConnection;
	private unfinishedButton unfinishedObservationsButton;
	private String patientName = "";
	private String patientCPR = "";
	private TextView nameTextView;
	private EditText cprEditText;
	private AlertDialog dialog = null;
	private MaxToksDBAdapter mtDBadapter;
	
	/**
	 * Attributes for AsyncTask
	 */
	private final String INSERT_PATIENT_DATA = "insertPatintData";
	private final String HISTORY = "histroy";
	private final String PRESCRIPTION = "precription";
	private final String UNFINISHED_PATIENT = "unfinishedPatient";
	private final String PRESRIPTION_CHECK_CPR = "precriptionCheckCpr"; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		startService(new Intent(this, SMSService.class));
		
		//i.compareTo(i);
		
		setContentView(R.layout.main);
		user = new User(this);
		DBConnection = new DataBaseConnection(user);
		mtDBadapter = new MaxToksDBAdapter(this);
	
		
		cprEditText = (EditText)findViewById(R.id.InsertCPRTextField);
		unfinishedObservationsButton = (unfinishedButton)findViewById(R.id.UnfinishedObservationsButton);		
		nameTextView = (TextView)findViewById(R.id.PatientNameTextView);
		
		cprEditText.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(keyCode == KeyEvent.KEYCODE_DEL){
					if(nameTextView.getText().length() != 0){
					nameTextView.setText("");
					disableButtons();
					mCurrentPatient = null;
					return true;
					}
				}
				return false;
			}
		});
		
		cprEditText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				EditText cprEditText = (EditText)findViewById(R.id.InsertCPRTextField);
				if(cprEditText.getText().length() == 10){
					enableButtons();
				}
				else{
					disableButtons();
				}
			}
		});
		
		try {
			String CPR = getIntent().getStringExtra("message");
			if(isCPR(CPR))
				patientCPR = CPR;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		String CPR = intent.getStringExtra("message");
		if(isCPR(CPR))
			patientCPR = CPR;
		super.onNewIntent(intent);
	}
	
	private Boolean isCPR(String CPR)
	{
		if(CPR.length() == 10 && isNumeric(CPR))
			return true;
		return false;
	}
	private boolean isNumeric(String str)
	{
		return str.matches("-?\\d+(.\\d+)?");
	}
	/**
	 * Starts InsetPatientData activity
	 * @param view
	 */
	public void viewData(View view)
	{
		EditText cprEditText = (EditText)findViewById(R.id.InsertCPRTextField);
		String cpr = cprEditText.getText().toString();
		if(cpr.length() != 0){
			if(mCurrentPatient != null)
			{
				Intent intent = new Intent();
		        intent.putExtra("patient", mCurrentPatient);
		        intent.setClass(this, InsertPatientData.class);
		        
		        startActivityForResult(intent, mPatientData);
			}
			else
			{
				String[] s = {cpr,INSERT_PATIENT_DATA};
				asynch task = new asynch();
				task.execute(s);
			}
		}
		else{
			Toast.makeText(this, getString(R.string.MainViewPatientChose), Toast.LENGTH_SHORT).show();
		}
	}
	
	/**
	 * Start FavoritePatient activity
	 * @param view
	 */
	public void favoritePatient(View view)
	{		
		Intent intent = new Intent();
		intent.setClass(this, FavoritePatient.class);
		startActivityForResult(intent, mFavoritePatient);
	}
	
	/**
	 * Start UnfinishedPatients activity
	 * @param view
	 */
	public void unfinishedObservations(View view)
	{		
		Intent intent = new Intent();
		intent.setClass(this, UnfinishedPatientActivity.class);
		startActivityForResult(intent, mUnfinishedPatient);
	}
	
	/**
	 * Start History activity
	 * @param view
	 */
	public void viewHistory(View view)
	{		
		EditText cprEditText = (EditText)findViewById(R.id.InsertCPRTextField);
		String cpr = cprEditText.getText().toString();
		if(cpr.length() != 0){
			if(mCurrentPatient != null)
			{
				Intent intent = new Intent();
		        intent.putExtra("patient", mCurrentPatient);
		        intent.setClass(this, History.class);
		        
		        startActivityForResult(intent, mFavoritePatient);
			}
			else
			{
				String[] s = {cpr, HISTORY};
				asynch task = new asynch();
				task.execute(s);
			}
		}
		else{
			Toast.makeText(this, getString(R.string.MainViewPatientChose), Toast.LENGTH_SHORT).show();
		}
	}
	
	/**
	 * Start prescription dialog, for entering max TOKS
	 * @param view
	 */
	public void Prescription(View view){
		asynch asyncDBC = new asynch();
		asyncDBC.execute(cprEditText.getText().toString(), PRESRIPTION_CHECK_CPR);
	}
	
	private void startPrescriptionDialog(){
	    String title = getString(R.string.PrescriptionDialogTitle) + " " + cprEditText.getText().toString().substring(0, 6) + "-" + cprEditText.getText().toString().substring(6); 
		LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.add_max_toks_dialog, null); 
		dialog = new AlertDialog.Builder(this)
        .setIcon(R.drawable.write_comment_white_icon)
        .setTitle(title)
        .setView(textEntryView)
        .setPositiveButton(R.string.generalSaveBtn, new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface mdialog, int whichButton) 
        	{
        		EditText toksEditText = (EditText)dialog.findViewById(R.id.MaxToksEditText);
        		Integer toks = Integer.parseInt(toksEditText.getText().toString());
        		if(toks > 0 && toks < 25){
        			asynch asyncDBC = new asynch();
        			asyncDBC.execute(cprEditText.getText().toString(), PRESCRIPTION, toks.toString()); 
        		}else{
        			Toast.makeText(MainView.this, getString(R.string.PrescriptionOutOfBounds), Toast.LENGTH_SHORT).show();
        		}
            }
         })
         .setNegativeButton(R.string.generalCancelBtn, new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int whichButton) 
             {
            	 
             }
         })
         .create();
		
		dialog.show();
		
		TextView oldToks = (TextView)dialog.findViewById(R.id.OldToksTextView);
		if(oldToks != null){
			
			try{
				mtDBadapter.openReadOnly();
				Cursor c = mtDBadapter.getMaxToks(cprEditText.getText().toString());
				if(c != null){
					oldToks.setTextColor(Color.WHITE);
					String oldvalue = c.getString(2);
					oldToks.setText("Old TOKS value: " + oldvalue);
				}
			}catch (Exception e) {
			}
			mtDBadapter.close();
		}
		
		(new Handler()).postDelayed(new Runnable() {

            public void run() 
            {
		        EditText comments = (EditText)dialog.findViewById(R.id.MaxToksEditText);
		
		        comments.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
		        comments.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
            }
        }, 0);
	}
	
	/**
	 * Log out the user
	 */
	public void logOut()
	{		
		user.logOut();
		user.setPassword("");
		
		Intent intent = new Intent();
        intent.setClass(this, LogIn.class);
        startActivityForResult(intent, mLogIn);
	}
	
	public void settingsView()
	{
		Intent settingsActivity = new Intent(getBaseContext(),
                Settings.class);
		startActivity(settingsActivity);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.setting:
	            settingsView();
	            return true;
	        case R.id.logOut:
	            logOut();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	protected void onResume() 
	{	
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		String s = prefs.getString("listPref", "");
		if(s.equals(((String[])getResources().getStringArray(R.array.SettingsUserLevel))[0]))
			user.setType(user.DOCTOR);
		else if (s.equals(((String[])getResources().getStringArray(R.array.SettingsUserLevel))[1]))
			user.setType(user.NURSE);
		
		if(prefs.getBoolean("checkboxPref", false))
		{
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}
		
		else
		{
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}
		
		if(user.isLoggedIn())
		{
			setTitle(getString(R.string.app_name) + " - " + user.getUserName().toString());
			if(user.getType().equals(user.DOCTOR)){
				Button button = (Button)findViewById(R.id.PatientPrescriptionButton);
				button.setVisibility(View.VISIBLE);
			}
			else if(user.getType().equals(user.NURSE)){
				Button button = (Button)findViewById(R.id.PatientPrescriptionButton);
				button.setVisibility(View.GONE);
			}
		}
		
		else
		{
			Intent intent = new Intent();
	        intent.setClass(this, LogIn.class);
	        
	        startActivityForResult(intent, mLogIn);
		}
		
		unfinishedObservationsButton.updateContent();
		unfinishedObservationsButton.setVisibility(unfinishedObservationsButton.shouldBeEnabled());
		
		if(mCurrentPatient != null)
		{
			nameTextView.setText(mCurrentPatient.getName());
			cprEditText.setText(mCurrentPatient.getCPR());
		}
		else
		{
			nameTextView.setText(patientName);
			cprEditText.setText(patientCPR);
		}
		
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		try {
			patientName = nameTextView.getText().toString();
			patientCPR = cprEditText.getText().toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onPause();
	}
	
	/**
	 * Clear the CPR number text view
	 * @param view
	 */
	public void clearCPRbox(View view){
		TextView nameTextView = (TextView)findViewById(R.id.PatientNameTextView);
		EditText cprEditText = (EditText)findViewById(R.id.InsertCPRTextField);
		
		mCurrentPatient = null;
		patientName = "";
		patientCPR = "";
		
		nameTextView.setText("");
		cprEditText.setText("");
		disableButtons();
	}
	
	private void enableButtons(){
		
		Button insertPDButton = (Button)findViewById(R.id.InsertPatientButton);
		Button histroyButton = (Button)findViewById(R.id.ShowPatientHistoryButton);
		Button prescriptionButton = (Button)findViewById(R.id.PatientPrescriptionButton);
		
		insertPDButton.setEnabled(true);
		histroyButton.setEnabled(true);
		prescriptionButton.setEnabled(true);
	}
	
	private void disableButtons(){
		Button insertPDButton = (Button)findViewById(R.id.InsertPatientButton);
		Button histroyButton = (Button)findViewById(R.id.ShowPatientHistoryButton);
		Button prescriptionButton = (Button)findViewById(R.id.PatientPrescriptionButton);
		
		insertPDButton.setEnabled(false);
		histroyButton.setEnabled(false);
		prescriptionButton.setEnabled(false);
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
		switch(requestCode){
		case mLogIn:
			 if(resultCode == RESULT_CANCELED){
				finish();
	    		System.exit(0);
			 }else if(resultCode == RESULT_OK){
				 Button prescriptionButton = (Button)findViewById(R.id.PatientPrescriptionButton);
				 User user = new User(this);
				 String type = user.getType();
				 if(type.equals("DOCTOR")){
					 prescriptionButton.setVisibility(View.VISIBLE);
				 }else{
					 prescriptionButton.setVisibility(View.GONE);
				 }
			 }
			break;
		case mFavoritePatient:
			if(resultCode == RESULT_OK){
				TextView nameTextView = (TextView)findViewById(R.id.PatientNameTextView);
	    		EditText cprEditText = (EditText)findViewById(R.id.InsertCPRTextField);
	    		
	    		mCurrentPatient = (Patient)data.getSerializableExtra("patient");
	    		
	    		nameTextView.setText(mCurrentPatient.getName());
	    		cprEditText.setText(mCurrentPatient.getCPR());
	    		
	    		enableButtons();
			}
    		break;
		case mPatientData:
			if(resultCode == RESULT_CANCELED){
			}
			else if(resultCode == RESULT_OK){
				Toast.makeText(this, R.string.MainViewPaitientDataSaving, Toast.LENGTH_SHORT).show();
			}
			break;
		case mUnfinishedPatient:
			if(resultCode == RESULT_OK){
	    		mCurrentPatient = (Patient)data.getSerializableExtra("patient");
	    		nameTextView.setText(mCurrentPatient.getName());
	    		cprEditText.setText(mCurrentPatient.getCPR());
	    		
	    		String[] s = {"", UNFINISHED_PATIENT};

	    		asynch task = new asynch();
		        task.execute(s);
			}
			break;
		}
    }
	
	private class asynch extends AsyncTask<String, Integer, Boolean>
	{
		private ProgressDialog mpd;
		private Integer res = 0;
		private Intent intent = new Intent();

		@Override
		protected void onPreExecute() {
			mpd = ProgressDialog.show(MainView.this, getString(R.string.HistoryViewProgressTitle), getString(R.string.PrescriptionProgressDialogCheckCpr), true, true);	
			mpd.setOnCancelListener(new OnCancelListener() {
			
				@Override
				public void onCancel(DialogInterface dialog) {
				}
			});
			super.onPreExecute();
		}

		@Override
		protected Boolean doInBackground(String... params) {
			
			if(params[1].contains(UNFINISHED_PATIENT)){
			    intent.putExtra("patient", mCurrentPatient);
			    res = 1;
			}else if(params[1].equals(INSERT_PATIENT_DATA)){
				String cpr = params[0];
				mCurrentPatient = DBConnection.patientInformation(cpr);
				res = 2;
			}else if(params[1].contains(HISTORY)){
				String cpr = params[0];
				mCurrentPatient = DBConnection.patientInformation(cpr);
				res = 3;
			}else if(params[1].equals(PRESCRIPTION)){
				mtDBadapter.open();
				String cpr = params[0];
				String toks = params[2];
				if(mtDBadapter.updateMaxToks(cpr, Integer.parseInt(toks))){
					mtDBadapter.close();
				}else{
					mtDBadapter.close();
					res = 6;
				}
			}else if(params[1].equals(PRESRIPTION_CHECK_CPR)){
				String cpr = params[0];
				Patient p = DBConnection.patientInformation(cpr);
				if(p != null){
					res = 4;
				}else{
					res = 5;
				}
			}
		return null;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			mpd.dismiss();
			
			switch (res) {
			case 1:
		        intent.putExtra("fromUnfinished", true);
		        intent.setClass(MainView.this, InsertPatientData.class);
		        startActivityForResult(intent, mPatientData);
				break;
			case 2:
				if(mCurrentPatient == null)
				{
					Toast d = Toast.makeText(MainView.this, getString(R.string.MainViewPatientNoExist), Toast.LENGTH_SHORT);
					d.setGravity(Gravity.CENTER, 0, 0);
					d.show();
				}
				else{
					Intent intent = new Intent();
			        intent.putExtra("patient", mCurrentPatient);
			        intent.setClass(MainView.this, InsertPatientData.class);
			        
			        startActivityForResult(intent, mPatientData);
				}
				break;
			case 3:
				if(mCurrentPatient == null)
				{
					Toast.makeText(MainView.this, getString(R.string.MainViewPatientNoExist), Toast.LENGTH_SHORT).show();
				}
				else{
					Intent intent = new Intent();
			        intent.putExtra("patient", mCurrentPatient);
			        intent.setClass(MainView.this, History.class);
			        
			        startActivityForResult(intent, mFavoritePatient);
				}
				break;
			case 4: // The cpr is correct and dialog box for Prescription can start
				startPrescriptionDialog();
				break;
			case 5:
				Toast.makeText(MainView.this, R.string.MainViewPatientNoExist, Toast.LENGTH_SHORT).show();
				break;
			case 6:
				Toast.makeText(MainView.this, getString(R.string.PrescriptionError), Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
			
			super.onPostExecute(result);
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) 
	{
		try {
			outState.putString("patientName", mCurrentPatient.getName());
			outState.putString("patientCPR", mCurrentPatient.getCPR());
		} 
		catch (Exception e) {
			outState.putString("patientName", patientName);
			outState.putString("patientCPR", patientCPR);
			e.printStackTrace();
		}
		
		super.onSaveInstanceState(outState);
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		try 
		{
			patientName = savedInstanceState.getString("patientName");
			patientCPR = savedInstanceState.getString("patientCPR");
			mCurrentPatient = new Patient(patientCPR, patientName);
		} 
		catch (Exception e) {
			patientName = "";
			e.printStackTrace();
		}
		super.onRestoreInstanceState(savedInstanceState);
	}
}